<template>
    <Header></Header>

    <!-- 未登录提示 -->
    <div v-if="!isUserLoggedIn" class="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div class="text-center">
            <svg class="mx-auto h-24 w-24 text-gray-400 dark:text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"></path>
            </svg>
            <h1 class="mt-4 text-2xl font-bold text-gray-900 dark:text-white">需要登录</h1>
            <p class="mt-2 text-gray-600 dark:text-gray-400">请先登录后查看喜欢的文章</p>
            <div class="mt-6">
                <button @click="router.push('/login')" 
                        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700">
                    前往登录
                </button>
            </div>
        </div>
    </div>

    <!-- 已登录用户的内容 -->
    <div v-else>
        <!-- 页面标题 -->
        <div class="bg-white dark:bg-gray-900">
        <div class="max-w-screen-xl mx-auto px-4 md:px-6 py-10">
            <h1 class="text-3xl md:text-4xl font-bold text-gray-900 dark:text-white mb-4">我喜欢的文章</h1>
            <p class="text-gray-600 dark:text-gray-400">{{ likeStats.total }} 篇喜欢的文章</p>
        </div>
    </div>

    <!-- 主内容区域 -->
    <main class="container max-w-screen-xl mx-auto px-4 md:px-6 py-4">
        <!-- grid 表格布局，分为 4 列 -->
        <div class="grid grid-cols-4 gap-7">
            <!-- 左边栏，占用 3 列 -->
            <div class="col-span-4 md:col-span-3 mb-3">
                <!-- 喜欢文章列表 -->
                <div v-if="likeArticles.length > 0" class="space-y-6">
                    <div v-for="(article, index) in likeArticles" :key="article.favoriteId" 
                         class="bg-white border border-gray-200 rounded-lg p-6 hover:shadow-lg transition-shadow dark:bg-gray-800 dark:border-gray-700">
                        <div class="flex flex-col md:flex-row gap-4">
                            <!-- 文章封面 -->
                            <div class="md:w-48 flex-shrink-0">
                                <a @click="goArticleDetailPage(article.articleId)" class="cursor-pointer">
                                    <img class="w-full h-32 md:h-36 object-cover rounded-lg" 
                                         :src="article.cover || '/default-cover.jpg'" 
                                         :alt="article.title" />
                                </a>
                            </div>
                            
                            <!-- 文章信息 -->
                            <div class="flex-1 min-w-0">
                                <div class="flex flex-col h-full">
                                    <!-- 标签 -->
                                    <div class="mb-3" v-if="article.tags && article.tags.length > 0">
                                        <span v-for="(tag, tagIndex) in article.tags" :key="tagIndex" 
                                              @click="goTagArticleListPage(tag)" 
                                              class="cursor-pointer bg-blue-100 text-blue-800 text-xs font-medium mr-2 px-2.5 py-0.5 
                                                     rounded hover:bg-blue-200 hover:text-blue-900 dark:bg-blue-900 
                                                     dark:hover:bg-blue-950 dark:text-blue-300">
                                            {{ tag }}
                                        </span>
                                    </div>
                                    
                                    <!-- 文章标题 -->
                                    <h2 class="text-xl font-bold text-gray-900 dark:text-white mb-2 line-clamp-2">
                                        <a @click="goArticleDetailPage(article.articleId)" 
                                           class="cursor-pointer hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                                            {{ article.title }}
                                        </a>
                                    </h2>
                                    

                                    
                                    <!-- 文章元信息和操作 -->
                                    <div class="mt-auto flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                                        <div class="flex items-center text-sm text-gray-500 dark:text-gray-400 space-x-4">
                                            <!-- 作者 -->
                                            <div class="flex items-center">
                                                <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                                    <path d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"/>
                                                </svg>
                                                {{ article.author }}
                                            </div>
                                            
                                            <!-- 发布时间 -->
                                            <div class="flex items-center">
                                                <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd"/>
                                                </svg>
                                                {{ formatDate(article.articleCreateTime) }}
                                            </div>
                                            
                                            <!-- 喜欢时间 -->
                                            <div class="flex items-center">
                                                <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                                    <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z"/>
                                                </svg>
                                                喜欢于 {{ formatDate(article.favoriteCreateTime) }}
                                            </div>
                                            
                                            <!-- 分类 -->
                                            <div v-if="article.categoryName" class="flex items-center">
                                                <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                                                    <path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z"/>
                                                </svg>
                                                {{ article.categoryName }}
                                            </div>
                                        </div>
                                        
                                        <!-- 操作按钮 -->
                                        <div class="flex items-center space-x-2">
                                            <button @click="goArticleDetailPage(article.articleId)"
                                                    class="px-3 py-1.5 text-sm text-blue-600 hover:text-blue-800 hover:bg-blue-50 
                                                           rounded border border-blue-300 hover:border-blue-400 transition-colors
                                                           dark:text-blue-400 dark:hover:text-blue-300 dark:border-blue-600 
                                                           dark:hover:bg-blue-900 dark:hover:border-blue-500">
                                                阅读
                                            </button>
                                            <button @click="removeLikeArticle(article)"
                                                    class="px-3 py-1.5 text-sm text-red-600 hover:text-red-800 hover:bg-red-50 
                                                           rounded border border-red-300 hover:border-red-400 transition-colors
                                                           dark:text-red-400 dark:hover:text-red-300 dark:border-red-600 
                                                           dark:hover:bg-red-900 dark:hover:border-red-500">
                                                取消喜欢
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 空状态 -->
                <div v-else class="text-center py-20">
                    <svg class="mx-auto h-24 w-24 text-gray-400 dark:text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z"/>
                    </svg>
                    <h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-white">还没有喜欢任何文章</h3>
                    <p class="mt-2 text-gray-500 dark:text-gray-400">开始浏览文章并点赞你喜欢的内容吧</p>
                    <div class="mt-6">
                        <a @click="router.push('/')" 
                           class="cursor-pointer inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            浏览文章
                        </a>
                    </div>
                </div>

                <!-- 分页（复用收藏页面的分页逻辑） -->
                <nav v-if="likeArticles.length > 0 && pagination.total > pagination.size" 
                     class="flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6 mt-8 rounded-lg dark:bg-gray-800 dark:border-gray-700">
                    <div class="flex flex-1 justify-between sm:hidden">
                        <button @click="goToPage(pagination.current - 1)" 
                                :disabled="pagination.current <= 1"
                                :class="['relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50',
                                         pagination.current <= 1 ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer']">
                            上一页
                        </button>
                        <button @click="goToPage(pagination.current + 1)" 
                                :disabled="pagination.current >= Math.ceil(pagination.total / pagination.size)"
                                :class="['relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50',
                                         pagination.current >= Math.ceil(pagination.total / pagination.size) ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer']">
                            下一页
                        </button>
                    </div>
                    <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
                        <div>
                            <p class="text-sm text-gray-700 dark:text-gray-300">
                                显示第 
                                <span class="font-medium">{{ (pagination.current - 1) * pagination.size + 1 }}</span>
                                -
                                <span class="font-medium">{{ Math.min(pagination.current * pagination.size, pagination.total) }}</span>
                                条，共
                                <span class="font-medium">{{ pagination.total }}</span>
                                条结果
                            </p>
                        </div>
                        <div>
                            <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">
                                <button @click="goToPage(pagination.current - 1)" 
                                        :disabled="pagination.current <= 1"
                                        :class="['relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0',
                                                 pagination.current <= 1 ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:text-gray-600']">
                                    <span class="sr-only">上一页</span>
                                    <svg class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                                        <path fill-rule="evenodd" d="M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z" clip-rule="evenodd"/>
                                    </svg>
                                </button>
                                <template v-for="page in getPageNumbers()" :key="page">
                                    <button v-if="page !== '...'" 
                                            @click="goToPage(page)"
                                            :class="['relative inline-flex items-center px-4 py-2 text-sm font-semibold ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0',
                                                     page === pagination.current ? 'z-10 bg-blue-600 text-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600' : 'text-gray-900 cursor-pointer hover:text-gray-600']">
                                        {{ page }}
                                    </button>
                                    <span v-else class="relative inline-flex items-center px-4 py-2 text-sm font-semibold text-gray-700 ring-1 ring-inset ring-gray-300 focus:outline-offset-0">
                                        ...
                                    </span>
                                </template>
                                <button @click="goToPage(pagination.current + 1)" 
                                        :disabled="pagination.current >= Math.ceil(pagination.total / pagination.size)"
                                        :class="['relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0',
                                                 pagination.current >= Math.ceil(pagination.total / pagination.size) ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:text-gray-600']">
                                    <span class="sr-only">下一页</span>
                                    <svg class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                                        <path fill-rule="evenodd" d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z" clip-rule="evenodd"/>
                                    </svg>
                                </button>
                            </nav>
                        </div>
                    </div>
                </nav>
            </div>

            <!-- 右边侧边栏，占用一列 -->
            <aside class="col-span-4 md:col-span-1">
                <!-- 喜欢统计 -->
                <div class="bg-white border border-gray-200 rounded-lg p-4 mb-4 dark:bg-gray-800 dark:border-gray-700">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-3">喜欢统计</h3>
                    <div class="space-y-2">
                        <div class="flex justify-between items-center">
                            <span class="text-gray-600 dark:text-gray-400">总喜欢数</span>
                            <span class="font-medium text-gray-900 dark:text-white">{{ likeStats.total }}</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-gray-600 dark:text-gray-400">本月喜欢</span>
                            <span class="font-medium text-gray-900 dark:text-white">{{ likeStats.thisMonth }}</span>
                        </div>
                    </div>
                </div>

                <!-- 分类 -->
                <CategoryListCard></CategoryListCard>

                <!-- 标签 -->
                <TagListCard></TagListCard>
            </aside>
        </div>
    </main>

    <!-- 返回顶部 -->
    <ScrollToTopButton></ScrollToTopButton>

    <Footer></Footer>
    </div>
</template>

<script setup>
import Header from '@/layouts/frontend/components/Header.vue'
import Footer from '@/layouts/frontend/components/Footer.vue'
import TagListCard from '@/layouts/frontend/components/TagListCard.vue'
import CategoryListCard from '@/layouts/frontend/components/CategoryListCard.vue'
import ScrollToTopButton from '@/layouts/frontend/components/ScrollToTopButton.vue'
import { getFavoriteList, removeFavorite } from '@/api/frontend/favorite'
import { useRouter } from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import { showMessage, showModel } from '@/composables/util'
import { getToken } from '@/composables/cookie'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 检查用户登录状态
const isUserLoggedIn = computed(() => {
    const token = getToken()
    return token && Object.keys(userStore.userInfo).length > 0
})

// 喜欢文章列表
const likeArticles = ref([])

// 分页信息
const pagination = ref({
    current: 1,
    size: 10,
    total: 0
})

// 喜欢统计
const likeStats = computed(() => {
    // 使用分页的总数作为总喜欢数
    const total = pagination.value.total
    // 当前页的本月喜欢数（这里只能统计当前页的，完整统计需要额外API）
    const thisMonth = likeArticles.value.filter(article => {
        const favoriteDate = new Date(article.favoriteCreateTime)
        const now = new Date()
        return favoriteDate.getMonth() === now.getMonth() && favoriteDate.getFullYear() === now.getFullYear()
    }).length
    
    return { total, thisMonth }
})

// 获取会话ID
function getSessionId() {
    let sessionId = localStorage.getItem('weblog_session_id')
    if (!sessionId) {
        sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        localStorage.setItem('weblog_session_id', sessionId)
    }
    return sessionId
}

// 获取喜欢列表
async function loadLikeList(page = 1) {
    try {
        const response = await getFavoriteList({
            current: page,
            size: pagination.value.size,
            sessionId: getSessionId(),
            type: 1 // 1-喜欢
        })
        
        if (response.success) {
            // 调试输出
            console.log('喜欢列表API响应:', response)
            
            // PageResponse格式：data字段包含文章列表，total等分页信息在根级别
            likeArticles.value = response.data || []
            pagination.value.current = response.current || page
            pagination.value.size = response.size || pagination.value.size
            pagination.value.total = response.total || 0
            
            console.log('解析后的喜欢文章:', likeArticles.value)
            console.log('分页信息:', pagination.value)
        } else {
            console.error('获取喜欢列表失败:', response.errorMessage)
            showMessage('获取喜欢列表失败：' + (response.errorMessage || '未知错误'), 'error')
        }
    } catch (error) {
        console.error('获取喜欢列表失败:', error)
    }
}

// 取消喜欢文章
async function removeLikeArticle(article) {
    try {
        const result = await showModel('确定要取消喜欢这篇文章吗？', 'warning', '确认操作')
        
        const response = await removeFavorite({
            articleId: article.articleId,
            sessionId: getSessionId(),
            type: 1 // 1-喜欢
        })
        
        if (response.success) {
            // 从列表中移除
            const index = likeArticles.value.findIndex(item => item.favoriteId === article.favoriteId)
            if (index > -1) {
                likeArticles.value.splice(index, 1)
            }
            // 如果当前页没有文章了，返回上一页
            if (likeArticles.value.length === 0 && pagination.value.current > 1) {
                loadLikeList(pagination.value.current - 1)
            }
            showMessage('取消喜欢成功', 'success')
        } else {
            console.error('取消喜欢失败:', response.errorMessage)
            showMessage('取消喜欢失败，请稍后重试', 'error')
        }
    } catch (error) {
        if (error === 'cancel') {
            // 用户取消操作，不需要处理
            return
        }
        console.error('取消喜欢失败:', error)
        showMessage('取消喜欢失败，请稍后重试', 'error')
    }
}

// 跳转到文章详情页
function goArticleDetailPage(articleId) {
    router.push('/article/' + articleId)
}

// 跳转到标签文章列表页
function goTagArticleListPage(tagName) {
    router.push({ path: '/tag/article/list', query: { name: tagName } })
}

// 跳转到指定页
function goToPage(page) {
    if (page >= 1 && page <= Math.ceil(pagination.value.total / pagination.value.size)) {
        loadLikeList(page)
    }
}

// 获取页码数组
function getPageNumbers() {
    const total = Math.ceil(pagination.value.total / pagination.value.size)
    const current = pagination.value.current
    const pages = []
    
    if (total <= 7) {
        for (let i = 1; i <= total; i++) {
            pages.push(i)
        }
    } else {
        if (current <= 4) {
            for (let i = 1; i <= 5; i++) {
                pages.push(i)
            }
            pages.push('...')
            pages.push(total)
        } else if (current >= total - 3) {
            pages.push(1)
            pages.push('...')
            for (let i = total - 4; i <= total; i++) {
                pages.push(i)
            }
        } else {
            pages.push(1)
            pages.push('...')
            for (let i = current - 1; i <= current + 1; i++) {
                pages.push(i)
            }
            pages.push('...')
            pages.push(total)
        }
    }
    
    return pages
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    })
}

// 页面加载时检查登录状态并获取喜欢列表
onMounted(() => {
    // 检查用户是否已登录
    if (!isUserLoggedIn.value) {
        showMessage('请先登录后查看喜欢的文章', 'warning')
        router.push('/login')
        return
    }
    
    loadLikeList()
})
</script>

<style scoped>
/* 文本行数限制 */
.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.line-clamp-3 {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style>
